# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
import pymysql
import random
from scrapy import signals
from .settings import MYSQL_IPS_CONNECT,COOKIE



class AllJdSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class AllJdDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.
    conn = None
    cursor = None
    proxy_list = []

    def __init__(self):
        self.conn = pymysql.Connect(host=MYSQL_IPS_CONNECT['host'], user=MYSQL_IPS_CONNECT['user'],
                                    port=MYSQL_IPS_CONNECT['port'], password=MYSQL_IPS_CONNECT['password'],
                                    db=MYSQL_IPS_CONNECT['db_name'],
                                    charset='utf8')
        self.cursor = self.conn.cursor()
        sql = 'select ip,port,http_type from ips'
        try:
            self.cursor.execute(sql)
            # 取数据库中所有的ip
            all_ip = self.cursor.fetchall()
            if not all_ip:
                raise ValueError('您没有代理ip了！')
            for ips in all_ip:
                ip, port, http_type = ips
                self.proxy_list.append(f"{http_type.lower()}s://{ip}:{port}")
        except Exception as e:
            print(e)

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        request.meta['http_proxy'] = random.choice(self.proxy_list)
        request.cookie = COOKIE

        return None

    def process_response(self, request, response, spider):
        if (spider.comment_url.split('?')[0] in request.url):
            if not response.text:
                # 如果评论页面数量数据取不到，换代理重新请求
                request.meta['http_proxy'] = random.choice(self.proxy_list)
                return request
        return response

    def process_exception(self, request, exception, spider):
        # 捕获到异常请求，换代理ip，重新发送请求
        request.meta['http_proxy'] = random.choice(self.proxy_list)
        return request

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
